package org.planaz.campusvoting.config;

import org.planaz.campusvoting.common.user.UserTransmitFilter;
import org.planaz.campusvoting.filter.TokenValidateFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class WebConfig {

	@Bean
	public FilterRegistrationBean UserTransmitFilter(){
		FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new UserTransmitFilter());//设置过滤器名称
		filterRegistrationBean.addUrlPatterns("/*");//配置过滤规则
		filterRegistrationBean.setOrder(10); //order的数值越小 则优先级越高
		return filterRegistrationBean;
	}
	@Bean
	public FilterRegistrationBean TokenValidateFilter(StringRedisTemplate stringRedisTemplate){
		FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new TokenValidateFilter(stringRedisTemplate));
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.setOrder(1);
		return filterRegistrationBean;
	}

	@Bean
	public CorsFilter corsFilter() {
		//1. 添加 CORS配置信息
		CorsConfiguration config = new CorsConfiguration();
		//放行哪些原始域
		config.addAllowedOriginPattern("*");
		//是否发送 Cookie
		config.setAllowCredentials(true);
		//放行哪些请求方式
		config.addAllowedMethod("*");
		//放行哪些原始请求头部信息
		config.addAllowedHeader("*");
		//暴露哪些头部信息
		config.addExposedHeader("*");
		//2. 添加映射路径
		UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
		corsConfigurationSource.registerCorsConfiguration("/**",config);
		//3. 返回新的CorsFilter
		return new CorsFilter(corsConfigurationSource);
	}
}